import time

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.Utils import QuestDriver

class QuestNew():
    url = ""
    driver = ""

    def __init__(self):
        self.url = "http://8.155.1.153:8081/survey/new?mode=survey"
        self.driver=QuestDriver.driver
        self.driver.get(self.url)

    #测试标题和简介能否正常输入
    def AddTitle(self):
        wait = WebDriverWait(self.driver,10)
        title = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"#editorContent .title .ql-editor")))
        title.clear()
        title.send_keys("数学水平调研")
        introd = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"#editorContent .prefix .ql-editor")))
        introd.clear()
        introd.send_keys("感谢参与调查问卷！")


    #测试添加单选题并返回新添加的题目元素
    def AddSingleChiose(self):
        wait = WebDriverWait(self.driver,10)
        # # 记录添加之前的题目元素
        # before_elements = self.driver.find_element(By.CSS_SELECTOR,
        #                                            "#editorContent > div > div > div:nth-child(2) > div")
        # before_list = before_elements.find_elements(By.XPATH, "./*")
        # before_rects = {(int(e.rect['x']), int(e.rect['y']), int(e.rect['width']), int(e.rect['height'])) for e in
        #                 before_list}
        #添加单选题
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"dl:nth-child(1) > div > div:nth-child(1)"))).click()
        #记录添加之后的题目元素
        after_elements = self.driver.find_element(By.CSS_SELECTOR,
                                                   "#editorContent > div > div > div:nth-child(2) > div").find_elements(By.XPATH, "./*")
        new_elem = None
        # for e in after_elements:
        #     r = (int(e.rect['x']), int(e.rect['y']), int(e.rect['width']), int(e.rect['height']))
        #     if r not in before_rects:
        #         new_elem = e
        #         break
        #
        # # 如果没通过 rect 找到（极少见），就取最后一个作为回退
        # if new_elem is None:
        #     new_elem = after_elements[-1]
        new_elem = after_elements[-1]

        text1=wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".q-title-wrap .ql-editor p"))).text.strip()
        assert text1 == "单选题"
        self.driver.find_element(By.CSS_SELECTOR,".q-title-wrap .ql-editor p").send_keys("1+1=?")
        QuestDriver.getScreenShot()
        return new_elem


    #测试添加多选题并返回新添加的题目元素
    def AddMulChiose(self):
        wait = WebDriverWait(self.driver, 10)

        # 添加多选题
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "dl:nth-child(1) > div > div:nth-child(2)"))).click()
        #记录添加题目之后的题目元素
        after_elements = self.driver.find_element(By.CSS_SELECTOR,
                                                  "#editorContent > div > div > div:nth-child(2) > div").find_elements(
            By.XPATH, "./*")

        #添加的题目元素一般都在题目列表的最后一个
        new_elem = after_elements[-1]
        text1 = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, ".q-title-wrap .ql-editor p"))).text.strip()
        assert text1 == "多选题"
        self.driver.find_element(By.CSS_SELECTOR,".q-title-wrap .ql-editor p").send_keys("大于2的数")
        QuestDriver.getScreenShot()
        return new_elem

    #测试添加文本题
    def AddSingleText(self):
        wait = WebDriverWait(self.driver,10)

        #添加单行文本框
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"dl:nth-child(2) > div > div:nth-child(1)"))).click()
        after_elements = self.driver.find_element(By.CSS_SELECTOR,
                                                  "#editorContent > div > div > div:nth-child(2) > div").find_elements(
            By.XPATH, "./*")
        # 添加的题目元素一般都在题目列表的最后一个
        new_elem = after_elements[-1]
        text1 = wait.until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, ".q-title-wrap .ql-editor p"))).text.strip()
        assert text1 == "单行文本题"
        self.driver.find_element(By.CSS_SELECTOR, ".q-title-wrap .ql-editor p").send_keys("你最喜欢的数字是什么？")
        QuestDriver.getScreenShot()
        return new_elem


    #设置单选题/多选题
    def SetSingleChiose(self,new_elem):
        wait = WebDriverWait(self.driver,10)
        new_elem.click()

        #添加单个选项
        parent_element = new_elem.find_element(By.CSS_SELECTOR, ".q-content > div > div")
        #添加之前的子元素的数量
        child_elements1 = parent_element.find_elements(By.XPATH, "./*")
        child_count1 = len(child_elements1)
        self.driver.find_element(By.CSS_SELECTOR,"#editorContent .q-operation > div > a:first-child").click()
        #添加之后子元素的数量
        child_elements2 = parent_element.find_elements(By.XPATH, "./*")
        child_count2 = len(child_elements2)
        assert (child_count2-child_count1) == 1

        #批量添加选项
        self.driver.find_element(By.CSS_SELECTOR,"#editorContent .q-operation a:nth-child(2)").click()
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,".ant-popover-message textarea"))).send_keys("3\n4")
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#editorContent .ant-popover-buttons .ant-btn-primary"))).click()
        #批量添加之后子元素的数量
        child_elements3 = parent_element.find_elements(By.XPATH, "./*")
        child_count3 = len(child_elements3)
        assert (child_count3-child_count2) == 2

        #删除其中一个选项
        #需要先鼠标悬停，让删除按钮显示出来
        actions = ActionChains(self.driver)
        option = child_elements3[2]  # 要删除的那个选项
        actions.move_to_element(option).perform()
        #调了好久！！！！！！！！！！！！！！！！！！！！！！！！！
        # 等待删除按钮出现（相对定位，避免全局冲突）
        delete_button = option.find_element(By.CSS_SELECTOR, "span.survey-icon.operate-icon[title='删除']")
        # 有些情况下 Selenium 认为按钮被遮挡，不可点，这里用 JS 执行点击更稳
        self.driver.execute_script("arguments[0].click();", delete_button)
        #删除一个选项之后的子元素的数量
        child_elements4 = parent_element.find_elements(By.XPATH, "./*")
        child_count4 = len(child_elements4)
        assert (child_count3 - child_count4) == 1

        #编辑设置选项的内容
        editor = parent_element.find_elements(By.CSS_SELECTOR, ".ql-editor")[-4]
        self.driver.execute_script("arguments[0].innerHTML = '1';", editor)
        editor = parent_element.find_elements(By.CSS_SELECTOR, ".ql-editor")[-3]
        self.driver.execute_script("arguments[0].innerHTML = '2';", editor)
        #调整选项的顺序
        self.AdjustChioseOrder(new_elem)
        QuestDriver.getScreenShot()


    #测试选项顺序的调整
    def AdjustChioseOrder(self,new_elem):
        wait = WebDriverWait(self.driver, 10)
        parent_element = new_elem.find_element(By.CSS_SELECTOR, ".q-content > div > div")
        options = parent_element.find_elements(By.XPATH, "./*")
        print(f"找到 {len(options)} 个选项")
        if len(options) < 2:
            print("选项数量不足，无法进行排序")
            return
        texts = [opt.text.strip() for opt in options if opt.text.strip()]
        print("拖拽前的顺序：", texts)

        option = options[0]
        # 选第一个选项的手柄作为 source
        ActionChains(self.driver).move_to_element(option).perform()
        handle = option.find_element(By.CSS_SELECTOR, "span")
        wait.until(EC.visibility_of(handle))

        # text_div = option.find_elements(By.XPATH, "./div")
        # option_text = ""
        # if text_div:
        #     option_text = text_div[0].text.strip()
        # print(f"找到手柄，对应选项内容: {option_text}")

        target = options[1]
        rect = target.rect
        target_x = rect['width'] // 2
        target_y_top = rect['height'] // 4  # 上 1/4 区域 → 插到前面
        target_y_bottom = rect['height'] * 3 // 4  # 下 3/4 区域 → 插到后面

        actions = ActionChains(self.driver)
        actions.click_and_hold(handle).move_to_element(target).move_by_offset(0, 0).release().perform()

        time.sleep(1)

        parent_element = new_elem.find_element(By.CSS_SELECTOR, ".q-content > div > div")
        new_options = parent_element.find_elements(By.XPATH, "./*")
        new_texts = [opt.text.strip() for opt in new_options if opt.text.strip()]
        print("拖拽后的顺序：", new_texts)


    #保存新建的问卷
    def SaveNewQuest(self):
        wait = WebDriverWait(self.driver,10)
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button.ant-btn-primary.ant-btn-sm"))).click()

        #判断是否成功保存
        url = self.driver.current_url
        return url

